using System;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Reflection;
using System.Windows.Forms;
using CXMLStudioIDE.BusinessLayer;
using CXMLStudioIDE.Common;
using CXMLStudioIDE.Common.Entities;
using CXMLStudioIDE.Customization;
using CXMLStudioIDE.DataAccessLayer;
using CXMLStudioIDE.Presenters;
using CXMLStudioIDE.Views;
using CXMLStudioIDE.WinFormsUI.CXMLStudioControls;
using CXMLStudioIDE.WinFormsUI.Docking;

namespace CXMLStudioIDE.Forms
{
    public partial class MainForm : Form, IMainView
    {
        #region Declarations

        public static PropertyWindowForm m_propertyWindow;
        public static DisplayContext m_currentcontext = DisplayContext.Deafult;
        private readonly DeserializeDockContent m_deserializeDockContent;
        private readonly OutputWindowForm m_outputWindow;
        private readonly MainPresenter m_presenter;
        private readonly SolutionExplorerForm m_projectExplorer;
        private readonly TaskListForm m_taskList;
        private readonly ToolboxForm m_toolbox;
        public String m_CXMLUser;
        public String m_Role;
        public SolutionManagerBL m_SolutionManager;
        private bool m_bSaveLayout = true;
        private BusinessEntityBuilder m_bebuilder;
        private DataDictionaryForm m_datadictionary;
        private frmProjectProperties m_projectProperties;
        private frmSolutionProperties m_solutionProperties;
        public TreeViewWindow m_tvWindow;
        //private Hashtable m_treeviewhash;

        #endregion

        #region Constructors

        public MainForm()
        {
            InitializeComponent();

            m_CXMLUser = Common.Common.GetNetworkUserId();
            var udal = new UserManagementDAL();
            m_Role = udal.GetRoleFromUser(m_CXMLUser);
            sl_txt_UserName.Text = m_CXMLUser;
            sl_txt_Role.Text = m_Role;
            m_SolutionManager = new SolutionManagerBL(m_CXMLUser);

            showRightToLeft.Checked = (RightToLeft == RightToLeft.Yes);
            RightToLeftLayout = showRightToLeft.Checked;
            m_projectExplorer = new SolutionExplorerForm(this);
            m_projectExplorer.RightToLeftLayout = RightToLeftLayout;
            m_deserializeDockContent = new DeserializeDockContent(GetContentFromPersistString);

            m_propertyWindow = new PropertyWindowForm();
            m_toolbox = new ToolboxForm();
            m_outputWindow = new OutputWindowForm();
            m_taskList = new TaskListForm();
            m_bebuilder = new BusinessEntityBuilder();
            m_datadictionary = new DataDictionaryForm(this);
            m_tvWindow = new TreeViewWindow(this);

            EnabledMenuItem("menuItemCloseSolution", false);
            EnabledMenuItem("menuItemSaveSolution", false);
            EnabledMenuItem("menuItemSaveAll", false);
            EnabledMenuItem("menuItemCloseProject", false);

            m_presenter = new MainPresenter(this);
            //m_treeviewhash = new Hashtable();

            /**  Subscribe to events MVP pattern**/
            //m_tvWindow.cxmlTreeView1.NodeMouseClick += new TreeNodeMouseClickEventHandler(OnCXMLTreeNodeClick);
            //m_tvWindow.cxmlTreeView1.AfterSelect += new TreeViewEventHandler(OnCXMLTreeNodeSelectionChange);
            m_projectExplorer.treeView1.NodeMouseDoubleClick += OnProjectExplorerNodeDoubleClick;
            m_projectExplorer.treeView1.KeyPress += OnProjectExplorerKeyPress;
            dockPanel.ActiveDocumentChanged += OnActiveDocumentChanged;
            m_propertyWindow.propertyGrid.PropertyValueChanged += OnPropertyValueChanged;
        }

        #endregion

        #region Update related methods

        public void UpdateMainForm()
        {
            if (m_SolutionManager.m_solution != null)
            {
                m_projectExplorer.PopulateTreeView(0,
                                                   m_SolutionManager.m_solution.GetProjects().GetProjectsDataTable(
                                                       m_SolutionManager.m_solution), m_SolutionManager.m_solution);
                if (m_datadictionary == null)
                {
                    m_datadictionary = new DataDictionaryForm(this);
                }
            }

            m_projectExplorer.Show(dockPanel);
        }

        #endregion

        #region Load related methods

        public void LoadProjectProperties(int i_TreeViewID)
        {
            if (m_projectProperties != null)
                m_projectProperties.Dispose();
            m_projectProperties = new frmProjectProperties(this, i_TreeViewID);
            m_projectProperties.Show(dockPanel);
        }

        public void LoadSolutionProperties()
        {
            if (m_solutionProperties != null)
                m_solutionProperties.Dispose();
            m_solutionProperties = new frmSolutionProperties(this);
            m_solutionProperties.Show(dockPanel);
        }

        #endregion

        private void menuItemExit_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void menuItemProjectExplorer_Click(object sender, EventArgs e)
        {
            m_projectExplorer.Show(dockPanel);
        }

        private void menuItemPropertyWindow_Click(object sender, EventArgs e)
        {
            m_propertyWindow.Show(dockPanel);
        }

        private void menuItemToolbox_Click(object sender, EventArgs e)
        {
            m_toolbox.Show(dockPanel);
        }

        private void menuItemOutputWindow_Click(object sender, EventArgs e)
        {
            m_outputWindow.Show(dockPanel);
        }

        private void menuItemTaskList_Click(object sender, EventArgs e)
        {
            m_taskList.Show(dockPanel);
        }

        private void menuItemAbout_Click(object sender, EventArgs e)
        {
            var aboutDialog = new AboutDialogForm();
            aboutDialog.ShowDialog(this);
        }

        private IDockContent FindDocument(string text)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                foreach (Form form in MdiChildren)
                    if (form.Text == text)
                        return form as IDockContent;

                return null;
            }
            else
            {
                foreach (IDockContent content in dockPanel.Documents)
                    if (content.DockHandler.TabText == text)
                        return content;

                return null;
            }
        }

        private void menuItemNew_Click(object sender, EventArgs e)
        {
        }

        private Document CreateNewDocument()
        {
            var dummyDoc = new Document();

            int count = 1;
            //string text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
            string text = "Document" + count;
            while (FindDocument(text) != null)
            {
                count++;
                //text = "C:\\MADFDKAJ\\ADAKFJASD\\ADFKDSAKFJASD\\ASDFKASDFJASDF\\ASDFIJADSFJ\\ASDFKDFDA" + count.ToString();
                text = "Document" + count;
            }
            dummyDoc.Text = text;
            return dummyDoc;
        }

        private Document CreateNewDocument(string text)
        {
            var dummyDoc = new Document();
            dummyDoc.Text = text;
            return dummyDoc;
        }

        private void menuItemOpen_Click(object sender, EventArgs e)
        {
        }

        private void OpenFile()
        {
            var openFile = new OpenFileDialog();

            openFile.InitialDirectory = Application.ExecutablePath;
            openFile.Filter = "rtf files (*.rtf)|*.rtf|txt files (*.txt)|*.txt|All files (*.*)|*.*";
            openFile.FilterIndex = 1;
            openFile.RestoreDirectory = true;

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                string fullName = openFile.FileName;
                string fileName = Path.GetFileName(fullName);

                if (FindDocument(fileName) != null)
                {
                    MessageBox.Show("The document: " + fileName + " has already opened!");
                    return;
                }

                var dummyDoc = new Document();
                dummyDoc.Text = fileName;
                if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
                {
                    dummyDoc.MdiParent = this;
                    dummyDoc.Show();
                }
                else
                    dummyDoc.Show(dockPanel);
                try
                {
                    dummyDoc.FileName = fullName;
                }
                catch (Exception exception)
                {
                    dummyDoc.Close();
                    MessageBox.Show(exception.Message);
                }
            }
        }

        private void menuItemFile_Popup(object sender, EventArgs e)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                menuItemClose.Enabled = menuItemCloseAll.Enabled = (ActiveMdiChild != null);
            }
            else
            {
                menuItemClose.Enabled = (dockPanel.ActiveDocument != null);
                menuItemCloseAll.Enabled = (dockPanel.DocumentsCount > 0);
            }
        }

        private IDockContent GetContentFromPersistString(string persistString)
        {
            if (persistString == typeof (SolutionExplorerForm).ToString())
                return m_projectExplorer;
            else if (persistString == typeof (PropertyWindowForm).ToString())
                return m_propertyWindow;
            else if (persistString == typeof (ToolboxForm).ToString())
                return m_toolbox;
            else if (persistString == typeof (OutputWindowForm).ToString())
                return m_outputWindow;
            else if (persistString == typeof (TaskListForm).ToString())
                return m_taskList;
            else
            {
                // DummyDoc overrides GetPersistString to add extra information into persistString.
                // Any DockContent may override this value to add any needed information for deserialization.

                string[] parsedStrings = persistString.Split(new[] {','});
                if (parsedStrings.Length != 3)
                    return null;

                if (parsedStrings[0] != typeof (Document).ToString())
                    return null;

                var dummyDoc = new Document();
                if (parsedStrings[1] != string.Empty)
                    dummyDoc.FileName = parsedStrings[1];
                if (parsedStrings[2] != string.Empty)
                    dummyDoc.Text = parsedStrings[2];

                return dummyDoc;
            }
        }

        //#endregion


        private void MainForm_Load(object sender, EventArgs e)
        {
            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");

            if (File.Exists(configFile))
                dockPanel.LoadFromXml(configFile, m_deserializeDockContent);
            m_propertyWindow.PropertyGridSelectedObject = null;
        }

        private void menuItemToolBar_Click(object sender, EventArgs e)
        {
            toolBar.Visible = menuItemToolBar.Checked = !menuItemToolBar.Checked;
        }

        private void menuItemStatusBar_Click(object sender, EventArgs e)
        {
            statusBar.Visible = menuItemStatusBar.Checked = !menuItemStatusBar.Checked;
        }

        private void toolBar_ButtonClick(object sender, ToolStripItemClickedEventArgs e)
        {
            if (e.ClickedItem == toolBarButtonNew)
                menuItemNew_Click(null, null);
            else if (e.ClickedItem == toolBarButtonOpen)
                menuItemOpen_Click(null, null);
            else if (e.ClickedItem == toolBarButtonSolutionExplorer)
                menuItemProjectExplorer_Click(null, null);
            else if (e.ClickedItem == toolBarButtonPropertyWindow)
                menuItemPropertyWindow_Click(null, null);
            else if (e.ClickedItem == toolBarButtonToolbox)
                menuItemToolbox_Click(null, null);
            else if (e.ClickedItem == toolBarButtonOutputWindow)
                menuItemOutputWindow_Click(null, null);
            else if (e.ClickedItem == toolBarButtonTaskList)
                menuItemTaskList_Click(null, null);
            else if (e.ClickedItem == toolBarButtonLayoutByCode)
                menuItemLayoutByCode_Click(null, null);
            else if (e.ClickedItem == toolBarButtonLayoutByXml)
                menuItemLayoutByXml_Click(null, null);
        }

        private void menuItemNewWindow_Click(object sender, EventArgs e)
        {
            var newWindow = new MainForm();
            newWindow.Text = newWindow.Text + " - New";
            newWindow.Show();
        }

        private void menuItemTools_Popup(object sender, EventArgs e)
        {
            menuItemLockLayout.Checked = !dockPanel.AllowEndUserDocking;
        }

        private void menuItemLockLayout_Click(object sender, EventArgs e)
        {
            dockPanel.AllowEndUserDocking = !dockPanel.AllowEndUserDocking;
        }

        private void menuItemLayoutByCode_Click(object sender, EventArgs e)
        {
            dockPanel.SuspendLayout(true);

            m_projectExplorer.Show(dockPanel, DockState.DockRight);
            m_propertyWindow.Show(m_projectExplorer.Pane, m_projectExplorer);
            m_toolbox.Show(dockPanel, new Rectangle(98, 133, 200, 383));
            m_outputWindow.Show(m_projectExplorer.Pane, DockAlignment.Bottom, 0.35);
            m_taskList.Show(m_toolbox.Pane, DockAlignment.Left, 0.4);

            CloseAllDocuments();
            Document doc1 = CreateNewDocument("Document1");
            Document doc2 = CreateNewDocument("Document2");
            Document doc3 = CreateNewDocument("Document3");
            Document doc4 = CreateNewDocument("Document4");
            doc1.Show(dockPanel, DockState.Document);
            doc2.Show(doc1.Pane, null);
            doc3.Show(doc1.Pane, DockAlignment.Bottom, 0.5);
            doc4.Show(doc3.Pane, DockAlignment.Right, 0.5);

            dockPanel.ResumeLayout(true, true);
        }

        private void menuItemLayoutByXml_Click(object sender, EventArgs e)
        {
            dockPanel.SuspendLayout(true);

            // In order to load layout from XML, we need to close all the DockContents
            CloseAllContents();

            Assembly assembly = Assembly.GetAssembly(typeof (MainForm));
            Stream xmlStream = assembly.GetManifestResourceStream("DockSample.Resources.DockPanel.xml");
            dockPanel.LoadFromXml(xmlStream, m_deserializeDockContent);
            if (xmlStream != null)
            {
                xmlStream.Close();
            }

            dockPanel.ResumeLayout(true, true);
        }

        private void SetSchema(object sender, EventArgs e)
        {
            CloseAllContents();

            if (sender == menuItemSchemaVS2005)
                Extender.SetSchema(dockPanel, Extender.Schema.VS2005);
            else if (sender == menuItemSchemaVS2003)
                Extender.SetSchema(dockPanel, Extender.Schema.VS2003);

            menuItemSchemaVS2005.Checked = (sender == menuItemSchemaVS2005);
            menuItemSchemaVS2003.Checked = (sender == menuItemSchemaVS2003);
        }

        private void SetDocumentStyle(object sender, EventArgs e)
        {
            DocumentStyle oldStyle = dockPanel.DocumentStyle;
            DocumentStyle newStyle;
            if (sender == menuItemDockingMdi)
                newStyle = DocumentStyle.DockingMdi;
            else if (sender == menuItemDockingWindow)
                newStyle = DocumentStyle.DockingWindow;
            else if (sender == menuItemDockingSdi)
                newStyle = DocumentStyle.DockingSdi;
            else
                newStyle = DocumentStyle.SystemMdi;

            if (oldStyle == newStyle)
                return;

            if (oldStyle == DocumentStyle.SystemMdi || newStyle == DocumentStyle.SystemMdi)
                CloseAllDocuments();

            dockPanel.DocumentStyle = newStyle;
            menuItemDockingMdi.Checked = (newStyle == DocumentStyle.DockingMdi);
            menuItemDockingWindow.Checked = (newStyle == DocumentStyle.DockingWindow);
            menuItemDockingSdi.Checked = (newStyle == DocumentStyle.DockingSdi);
            menuItemSystemMdi.Checked = (newStyle == DocumentStyle.SystemMdi);
            menuItemLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
            menuItemLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
            toolBarButtonLayoutByCode.Enabled = (newStyle != DocumentStyle.SystemMdi);
            toolBarButtonLayoutByXml.Enabled = (newStyle != DocumentStyle.SystemMdi);
        }

        private void menuItemCloseAllButThisOne_Click(object sender, EventArgs e)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                Form activeMdi = ActiveMdiChild;
                foreach (Form form in MdiChildren)
                {
                    if (form != activeMdi)
                        form.Close();
                }
            }
            else
            {
                foreach (IDockContent document in dockPanel.DocumentsToArray())
                {
                    if (!document.DockHandler.IsActivated)
                        document.DockHandler.Close();
                }
            }
        }

        private void menuItemShowDocumentIcon_Click(object sender, EventArgs e)
        {
            dockPanel.ShowDocumentIcon = menuItemShowDocumentIcon.Checked = !menuItemShowDocumentIcon.Checked;
        }

        private void showRightToLeft_Click(object sender, EventArgs e)
        {
            CloseAllContents();
            if (showRightToLeft.Checked)
            {
                RightToLeft = RightToLeft.No;
                RightToLeftLayout = false;
            }
            else
            {
                RightToLeft = RightToLeft.Yes;
                RightToLeftLayout = true;
            }
            m_projectExplorer.RightToLeftLayout = RightToLeftLayout;
            showRightToLeft.Checked = !showRightToLeft.Checked;
        }

        private void exitWithoutSavingLayout_Click(object sender, EventArgs e)
        {
            m_bSaveLayout = false;
            Close();
            m_bSaveLayout = true;
        }

        private void tsmProjectNew_Click(object sender, EventArgs e)
        {
            var npf = new NewProjectForm(this);
            npf.Show();
        }

        private void dockPanel_ActiveContentChanged(object sender, EventArgs e)
        {
            txt_Status.Text = "";
        }

        private void toolBarButtonNew_Click(object sender, EventArgs e)
        {
        }

        private void menuItemTreeView_Click(object sender, EventArgs e)
        {
            m_tvWindow.Show(dockPanel);
        }

        private void menuItemSolution_Click(object sender, EventArgs e)
        {
            var nsf = new NewSolutionForm(this);
            nsf.Show();
        }

        public void NewTextFile(string text)
        {
            Document dummyDoc = null;
            dummyDoc = text == null ? CreateNewDocument() : CreateNewDocument(text);
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                dummyDoc.MdiParent = this;
                dummyDoc.Show();
            }
            else
                dummyDoc.Show(dockPanel);
        }

        private void menuItemNewFile_Click(object sender, EventArgs e)
        {
            var nff = new NewFileForm(this);
            nff.Show();
        }

        private void menuItemSolAddNewProj_Click(object sender, EventArgs e)
        {
            var npf = new NewProjectForm(this);
            npf.Show();
        }

        public DockPanel GetDockPanel()
        {
            return dockPanel;
        }

        public void EnabledMenuItem(string menuitemname, bool enabled)
        {
            ToolStripItem[] it = MainMenuStrip.Items.Find(menuitemname, true);
            if (it.Length > 0)
            {
                var mi = it[0] as ToolStripMenuItem;
                if (mi != null) mi.Enabled = enabled;
            }
        }

        private void menuItemSaveSolution_Click(object sender, EventArgs e)
        {
            //CXMLStudioIDE.DataAccessLayer.CXMLStudioDAL dal = new CXMLStudioDAL();
            //dal.SaveSolution(this.m_solution, m_busentities);
        }

        private void menuItemNewProject_Click(object sender, EventArgs e)
        {
            if (m_SolutionManager.m_solution != null)
            {
                DialogResult result = MessageBox.Show("Save current solution?", "CXMLStudioIDE - Confirm save Solution",
                                                      MessageBoxButtons.YesNoCancel);
                if (result == DialogResult.Yes || result == DialogResult.No)
                {
                    if (result == DialogResult.Yes)
                    {
                        //TODO: Call save solution here
                    }
                    CloseSolution();
                }
            }
            var npf = new NewProjectForm(this);
            npf.Show();
        }

        private void toolBarButtonSave_Click(object sender, EventArgs e)
        {
            foreach (IDockContent document in dockPanel.DocumentsToArray())
            {
                //    document.DockHandler.Close();
                if (document.DockHandler.IsActivated)
                {
                    switch (document.DockHandler.Form.Name)
                    {
                        case "frmProjectProperties":
                            if (m_projectProperties != null)
                                m_projectProperties.SaveChanges();
                            break;
                        case "DataDictionaryForm":
                            if (m_datadictionary != null)
                            {
                                m_datadictionary.Save(false);
                            }
                            break;
                        case "DummyDoc":
                            var doc = ActiveMdiChild as Document;
                            if (doc != null) 
                                doc.SaveDocToXml(null, true);
                            break;
                    }
                }
            }
        }

        public string GetActiveDocumentName()
        {
            if (ActiveMdiChild != null) return ActiveMdiChild.Name;
            return null;
        }

        private void toolStripMenuItem4_Click(object sender, EventArgs e)
        {
            if (m_datadictionary == null)
            {
                m_datadictionary = new DataDictionaryForm(this);
            }
            m_datadictionary.Show(dockPanel);
        }

        private void toolStripMenuItem9_Click(object sender, EventArgs e)
        {
            NewFormDesignerForm();
        }

        public void SetStatus(string status)
        {
            txt_Status.Text = status;
        }

        public void ClearStatus()
        {
            txt_Status.Text = "";
        }

        private void MainForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            CloseAllContents();
        }

        private void toolStripMenuItem6_Click(object sender, EventArgs e)
        {
            CXMLTreeNode rootnode = CurrentRootNode;
            if (rootnode != null)
            {
                NewGoldEntryForm(rootnode, null, null,AddInstanceForm.AddInstanceMode.None);
            }
            else
            {
                NewGoldEntryForm(null, null, null, AddInstanceForm.AddInstanceMode.None);
            }
        }

        private void existingProjectToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var apf = new NewProjectFromExistingForm(this);
            apf.Show(dockPanel);
        }

        #region events

        public event TreeNodeMouseClickEventHandler OnCXMLTreeNodeClick;
        public event TreeViewEventHandler OnCXMLTreeNodeSelectionChange;
        public event TreeNodeMouseClickEventHandler OnProjectExplorerNodeDoubleClick;
        public event EventHandler OnActiveDocumentChanged;
        public event KeyPressEventHandler OnProjectExplorerKeyPress;
        public event PropertyValueChangedEventHandler OnPropertyValueChanged;
        public event FormDesigner.OnFormCompletedEventHandler OnFormCompleted;
        public event FormDesigner.OnEntityDroppedEventHandler OnEntityDroppedInFormDesigner;
        public event GoldEntryForm.OnFormCompletedEventHandler OnGoldFormCompleted;
        public event GoldEntryForm.OnGoldFormLoadingEventHandler OnGoldFormLoading;
        public event GoldEntryForm.OnInstanceAddedEventHandler OnInstanceAdded;
        public event CXMLTreeView.OnTreeViewUpdatedEventHandler OnTreeViewUpdated;
        public event CXMLTreeView.OnTreeNodeHoverEventHandler OnTreeNodeHover;
        public event CXMLTreeView.OnTreeViewMouseMoveEventHandler OnTreeViewMouseMove;
        public event AddInstanceForm.OnAddInstanceEventHandler OnAddInstance;

        #endregion

        #region Properties

        public string TreeViewWindowTitle
        {
            set
            {
                if (m_tvWindow != null)
                {
                    m_tvWindow.Text = value;
                    m_tvWindow.TabText = value;
                }
            }
        }

        public DisplayContext Context
        {
            get { return m_currentcontext; }
            set { m_currentcontext = value; }
        }

        public TreeNode ProjectExplorerSelectedNode
        {
            get { return m_projectExplorer.treeView1.SelectedNode; }
        }

        public object PropertyGridSelectedObject
        {
            get { return m_propertyWindow.PropertyGridSelectedObject; }
            set { m_propertyWindow.PropertyGridSelectedObject = value; }
        }

        public string TreeViewToolTipText
        {
            get
            {
                if (m_tvWindow != null && m_tvWindow.toolTip1 != null)
                {
                    return m_tvWindow.toolTip1.GetToolTip(m_tvWindow.cxmlTreeView1);
                }
                return "";
            }
            set
            {
                if (m_tvWindow != null && m_tvWindow.toolTip1 != null)
                {
                    m_tvWindow.toolTip1.SetToolTip(m_tvWindow.cxmlTreeView1, value);
                }
            }
        }

        public CXMLTreeNode CurrentRootNode
        {
            get
            {
                if (m_tvWindow != null && m_tvWindow.cxmlTreeView1 != null && m_tvWindow.cxmlTreeView1.Nodes.Count > 0)
                {
                    return m_tvWindow.cxmlTreeView1.Nodes[0] as CXMLTreeNode;
                }
                return null;
            }
        }

        public GoldEntryForm CallingGoldForm { get; set; }
        public CXMLTreeNode CallingCXMLTreeNode { get; set; }
        public AddInstanceForm.AddInstanceMode MyAddInstanceMode { get; set; }

        #endregion

        #region Methods

        public void SetFocusOnTreeView(CXMLTreeNode node)
        {
            if (m_tvWindow != null)
            {
                m_tvWindow.Focus();
                m_tvWindow.Select();
                //m_tvWindow.cxmlTreeView1.Focus();
                //m_tvWindow.cxmlTreeView1.Select();
                m_tvWindow.cxmlTreeView1.SelectedNode = node;
            }
        }

        public void ShowTreeView()
        {
            if (m_tvWindow != null)
            {
                m_tvWindow.Show(dockPanel);
            }
        }

        public void ShowDataDictionary()
        {
            if (m_datadictionary == null)
            {
                m_datadictionary = new DataDictionaryForm(this);
            }
            m_datadictionary.Show(dockPanel);
        }

        public void ShowPropertyWindow()
        {
            if (m_propertyWindow != null)
            {
                m_propertyWindow.Show(dockPanel);
            }
        }

        public void UpdateDataDictionary(BusinessEntity be)
        {
            if (m_datadictionary == null)
            {
                m_datadictionary = new DataDictionaryForm(this);
            }
            //this.Invoke((MethodInvoker)delegate { m_datadictionary.UpdateDataDictionary(be); });
            m_datadictionary.UpdateDataDictionary(be);
        }

        public BusinessEntity GetCurrentTreeViewBusinessEntity()
        {
            if (m_tvWindow != null && m_tvWindow.cxmlTreeView1.Nodes.Count > 0)
            {
                var root = m_tvWindow.cxmlTreeView1.Nodes[0] as CXMLTreeNode;
                if (root != null && root.BusinessEntity != null)
                {
                    return root.BusinessEntity;
                }
            }
            return null;
        }

        public void LoadTreeView(BusinessEntity be, DisplayContext context, Type EntityType,object instance)
        {
            /** Check if this treeview is already in array, if not then create it and load it 
             *  otherwise set the active treeview to the corresponding one **/
            int TreeViewId = m_tvWindow.GetTreeViewId(be, context);
            if (TreeViewId == -1)
            {
                m_tvWindow.InitCXMLTreeView(context);
                m_tvWindow.cxmlTreeView1.NodeMouseClick += OnCXMLTreeNodeClick;
                m_tvWindow.cxmlTreeView1.AfterSelect += OnCXMLTreeNodeSelectionChange;
                m_tvWindow.cxmlTreeView1.OnTreeViewUpdated += OnTreeViewUpdated;
                m_tvWindow.cxmlTreeView1.OnTreeNodeHover += OnTreeNodeHover;
                //m_tvWindow.cxmlTreeView1.OnTreeViewMouseMove += OnTreeViewMouseMove;
                IntPtr handle = m_tvWindow.cxmlTreeView1.Handle;
                //Display the progress panel
                m_tvWindow.StartProgress();
                m_tvWindow.cxmlTreeView1.UpdateTreeView(be, context, EntityType,instance);
            }
            else
            {
                m_tvWindow.SetActiveTreeView(TreeViewId);
                BusinessEntity b = GetCurrentTreeViewBusinessEntity();
                if (b != null)
                {
                    SelectSolutionExplorerNodeById(b.TreeViewId);
                }
            }
        }

        public void StopTreeViewProgressBar()
        {
            m_tvWindow.StopProgress();
        }

        public void NewFormDesignerForm()
        {
            ShowDataDictionary();
            var designer = new FormDesigner(this, null);
            designer.MaximumSize = new Size(0, 0);
            designer.AutoSize = true;
            designer.Name = "FormDesigner";
            designer.Text = "Form Designer";
            designer.Show(dockPanel);
            designer.OnFormCompleted += m_presenter.OnFormCompleted;
            designer.OnEntityDroppedInFormDesigner += m_presenter.OnEntityDroppedInFormDesigner;
        }

        public void NewAddInstanceForm(CXMLTreeNode node)
        {
            var aif = new AddInstanceForm(this, node);
            aif.OnAddInstance += OnAddInstance;
            aif.Show();
        }

        public void NewGoldEntryForm(CXMLTreeNode node, GoldEntryForm callingForm, CXMLTreeNode callingNode,CXMLStudioIDE.Forms.AddInstanceForm.AddInstanceMode mode)
        {
            GoldEntryForm goldform = null;
            AddInstanceArgs args = null;
            if(callingNode!=null && callingForm!= null && mode != null)
            {
                args = new AddInstanceArgs(null,callingNode,callingForm,mode);
            }
            if (node == null)
            {
                goldform = new GoldEntryForm(this, null);
            }
            else
            {
                if (args != null)
                {
                    goldform = new GoldEntryForm(this, node,args);
                }else
                {
                    goldform = new GoldEntryForm(this,node);
                }
            }
            goldform.MaximumSize = new Size(0, 0);
            goldform.AutoSize = true;
            goldform.Name = "GoldEntry";
            goldform.Text = "Gold Entry";
            goldform.OnGoldFormCompleted += m_presenter.OnGoldFormCompleted;
            goldform.OnGoldFormLoading += m_presenter.OnGoldFormLoading;
            goldform.OnInstanceAdded += m_presenter.OnGoldInstanceAdded;
            goldform.Show(dockPanel);
            if (node != null && node.BusinessEntity != null)
            {
                goldform.LoadGoldForm(node);
            }
            goldform.Refresh();
            this.Refresh();
        }

        public void AddInstanceTreeToNode(BusinessEntity be, CXMLTreeNode RootNode)
        {
            m_tvWindow.cxmlTreeView1.PrepareForInstances(null, be, RootNode);
        }

        public void ResetSolutionExplorerNodesColor()
        {
            BusinessEntityCollection bec = m_SolutionManager.m_solution.GetBusinessEntitiesInSolution();
            if(bec!=null)
            {
                foreach(BusinessEntity be in bec)
                {
                    if(be.TreeViewId > 0)
                    {
                        TreeNode[] nodes = m_projectExplorer.treeView1.Nodes.Find(be.TreeViewId.ToString(), true);
                        if(nodes.Length > 0)
                        {
                            nodes[0].BackColor = Color.Transparent;
                        }
                    }
                }
            }
        }

        public void SelectSolutionExplorerNodeById(int treeViewId)
        {
            if(m_projectExplorer != null && m_projectExplorer.treeView1 !=null)
            {
                m_projectExplorer.Select();
                TreeNode[] nodes = m_projectExplorer.treeView1.Nodes.Find(treeViewId.ToString(),true);
                foreach(TreeNode n in nodes)
                {
                    ResetSolutionExplorerNodesColor();
                    m_projectExplorer.treeView1.Select();
                    m_projectExplorer.treeView1.SelectedNode = n;
                    n.BackColor = System.Drawing.Color.Yellow;
                }
                m_projectExplorer.Update();
            }
        }
        public void SetTreeViewSelectedNode(CXMLTreeNode node)
        {
            if(m_tvWindow!= null && m_tvWindow.cxmlTreeView1 !=null)
            {
                m_tvWindow.cxmlTreeView1.Select();
                m_tvWindow.cxmlTreeView1.SelectedNode = node;
                node.EnsureVisible();
                m_tvWindow.Update();
                m_tvWindow.Focus();
            }
        }

        #endregion

        #region Test methods

        private void openGoldEntryFormToolStripMenuItem_Click(object sender, EventArgs e)
        {
            CXMLTreeNode places = new CXMLTreeNode();
            places.Name = "Places";
            AddInstanceForm aif = new AddInstanceForm(this,places);
            aif.Show();
            //string fileName = null;
            //try
            //{
            //    // Open File Dialog
            //    var dlg = new OpenFileDialog();
            //    CXMLTreeNode node = null;
            //    GoldEntryForm gef = null;
            //    dlg.DefaultExt = "xml";
            //    dlg.Filter = "Xml Files|*.xml";
            //    if (dlg.ShowDialog() == DialogResult.OK)
            //        fileName = dlg.FileName;

            //    if (fileName == null)
            //        return;
            //    if (m_tvWindow != null && m_tvWindow.cxmlTreeView1 != null && m_tvWindow.cxmlTreeView1.Nodes.Count > 0)
            //    {
            //        node = m_tvWindow.cxmlTreeView1.Nodes[0] as CXMLTreeNode;
            //    }
            //    if (node == null)
            //    {
            //        gef = new GoldEntryForm(this, null, null, null);
            //    }
            //    else
            //    {
            //        gef = new GoldEntryForm(this, node, null, null);
            //    }
            //    gef.Show(dockPanel);
            //}
            //catch (Exception ex)
            //{
            //    MessageBox.Show("Error in creating new host", "CXMLStudio", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //}
        }

        #endregion

        #region Close related methods

        private void menuItemCloseSolution_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(this, "Are you sure you want to close Solution?",
                                                  "CXMLStudioIDE - Confirm close Solution", MessageBoxButtons.YesNo,
                                                  MessageBoxIcon.Question);
            if (result == DialogResult.Yes)
            {
                CloseSolution();
            }
        }

        public void CloseSolution()
        {
            if (m_SolutionManager.m_solution != null)
            {
                m_SolutionManager.m_solution = null;
                m_tvWindow.Hide();
                Text = "CXMLStudio IDE";
                EnabledMenuItem("menuItemCloseSolution", false);
                EnabledMenuItem("menuItemSolution", false);
                EnabledMenuItem("menuItemSaveSolution", false);
                EnabledMenuItem("menuItemSaveAll", false);
                m_projectExplorer.ClearTreeView();
                if (m_propertyWindow != null)
                    m_propertyWindow.Hide();
                if (m_datadictionary != null)
                {
                    m_datadictionary.FinalizeComponents();
                    m_datadictionary.Close();
                    //m_datadictionary.Dispose();
                    m_datadictionary = null;
                }
            }
        }

        private void CloseProject()
        {
            if (m_SolutionManager.m_project != null)
            {
                m_SolutionManager.m_project = null;
                m_tvWindow.Hide();
                m_projectExplorer.ClearTreeView();
                EnabledMenuItem("menuItemCloseProject", false);
            }
        }

        private void menuItemCloseProject_Click(object sender, EventArgs e)
        {
            DialogResult result = MessageBox.Show(this, "Save current project?", "CXMLStudioIDE - Confirm save Project",
                                                  MessageBoxButtons.YesNoCancel, MessageBoxIcon.Question);
            if (result == DialogResult.Yes || result == DialogResult.No)
            {
                if (result == DialogResult.Yes)
                {
                    //TODO: Call save solution here
                }
                CloseProject();
            }
        }

        private void CloseAllContents()
        {
            // we don't want to create another instance of tool window, set DockPanel to null
            m_projectExplorer.DockPanel = null;
            m_propertyWindow.DockPanel = null;
            m_toolbox.DockPanel = null;
            m_outputWindow.DockPanel = null;
            m_taskList.DockPanel = null;
            m_datadictionary = null;

            // Close all other document windows
            CloseAllDocuments();
        }

        private void MainForm_Closing(object sender, CancelEventArgs e)
        {
            string configFile = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "DockPanel.config");
            if (m_bSaveLayout)
                dockPanel.SaveAsXml(configFile);
            else if (File.Exists(configFile))
                File.Delete(configFile);
        }

        private void menuItemClose_Click(object sender, EventArgs e)
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                if (ActiveMdiChild != null) ActiveMdiChild.Close();
            }
            else if (dockPanel.ActiveDocument != null)
                dockPanel.ActiveDocument.DockHandler.Close();
        }

        private void menuItemCloseAll_Click(object sender, EventArgs e)
        {
            CloseAllDocuments();
        }

        public void SetActiveDocument(Form formtoshow)
        {
            foreach (Form form in MdiChildren)
            {
                if (form.Equals(formtoshow))
                {
                    form.Activate();
                    OnActiveDocumentChanged(form, null);
                }
            }
        }

        private void CloseAllDocuments()
        {
            if (dockPanel.DocumentStyle == DocumentStyle.SystemMdi)
            {
                foreach (Form form in MdiChildren)
                    form.Close();
            }
            else
            {
                for (int index = dockPanel.Contents.Count - 1; index >= 0; index--)
                {
                    if (dockPanel.Contents[index] is IDockContent)
                    {
                        IDockContent content = dockPanel.Contents[index];
                        content.DockHandler.Close();
                    }
                }
            }
        }

        public void CloseDataDictionary()
        {
            if (m_datadictionary != null)
            {
                m_datadictionary.FinalizeComponents();
                m_datadictionary = null;
            }
        }

        #endregion

        #region Open related methods

        private void menuItemOpenFile_Click(object sender, EventArgs e)
        {
            OpenFile();
        }

        private void menuItemOpenSolution_Click(object sender, EventArgs e)
        {
            new frmOpenSolution(this).Show();
        }

        #endregion
    }
}